package com.ebook.server.service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.ebook.core.domain.Book;
import com.ebook.core.domain.Order;
//TODO: impl
@Service
public class OrderService {
	private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm");

	@Resource
	private JdbcTemplate jdbcTemplate;

	@SuppressWarnings("unused")
	public Order getOrderById(int oid) {
		String sql = "select * from orders where id=?";
		Order order = null;
		
		try {
			Map<String, Object> oMap = jdbcTemplate.queryForMap(sql, oid);
			Timestamp ct = (Timestamp)oMap.get("create_time");
//			Timestamp pt = (Timestamp)oMap.get("pay_time");
			int status = (Integer)oMap.get("status");
//			int tm = (Integer)oMap.get("total_amount");
//			int tn = (Integer)oMap.get("total_num");
			order = new Order();
			order.setId(oid);
			order.setCreateTime(SDF.format(ct));
//			String ptStr = pt == null ? "" : SDF.format(pt);
//			order.setPayTime(ptStr);

			order.setStatus(status);
			
			
			sql = "select b.* from orders_book as o, book as b where o.orderid=? and o.bookid=b.id";
			List<Map<String, Object>> bMaps = jdbcTemplate.queryForList(sql, oid);
						
			if (bMaps != null) {
				double totalAmount = 0.0;
				for (Map<String, Object> bMap : bMaps) {
					int id = (Integer)bMap.get("id");
					String name = (String)bMap.get("name");
					double price = (Double)bMap.get("price");
					totalAmount += price;
					
					Book b = new Book(); //TODO: impl
					order.getBooks().add(b);
				}
				order.setTotalAmount(totalAmount);
			}
			order.setTotalNum(order.getBooks().size());

		} catch (DataAccessException e) {
			e.printStackTrace();
			return null;
		}
		return order;
	}
	
	public List<Order> getOrdersByUserId(int uid) {
		List<Order> orders = new ArrayList<Order>();
		
		String sql = "select id from orders where userid=? order by id desc";
		try {
			List<Map<String, Object>> vals = jdbcTemplate.queryForList(sql, uid);
			if (vals != null) {
				for (Map<String, Object> val : vals) {
					int oid = (Integer)val.get("id");
					Order o = getOrderById(oid);
					
					if (o != null) {
						o.setUserId(uid);
						orders.add(o);
					}
				}
			}
		} catch (DataAccessException e) {
			e.printStackTrace();
			return new ArrayList<Order>();
		}
		return orders;
	}
	
	public Order createdOrder(int uid, List<Book> books, double totalAmount) {
		if (books.isEmpty()) {
			return null;
		}
		
		Order order = new Order();
		order.setUserId(uid);
		order.setBooks(books);
		order.setTotalAmount(totalAmount);
		order.setTotalNum(books.size());

		String t = SDF.format(new Date());
		String sql = "insert into orders (userid,create_time, status) values (?,?,?);";
		
		try {
			jdbcTemplate.update(sql, uid, t, 1);
			
			sql = "select max(id) from orders;";
			int orderId = jdbcTemplate.queryForInt(sql);
			order.setId(orderId);
			
			String sql1 = "insert into orders_book (orderid,bookid) values (?,?);";
			for (Book b : books) {
				jdbcTemplate.update(sql1, orderId, b.getId());
			}
			
		} catch (DataAccessException e) {
			e.printStackTrace();
			return null;
		}

		return order;
	}
}
